# 导入socket库
import socket
import threading
import time
import datetime
import rtmp


class SocketClient:

    def __init__(self, ip, port):
        self.IP = ip
        self.PORT = port
        self.cvRtmp = rtmp.CvRtmp('rtmp://101.132.123.218:1936/hls')
        self.isOnline = False

    """ socket 建立链接 """

    def connect(self):
        while True:
            server2 = (self.IP, self.PORT)
            global socket_client2
            socket_client2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            try:
                socket_client2.connect(server2)
            except Exception as message:
                print('连接服务器报错%s' % message)
                time.sleep(1)
                continue
            else:
                print('连接服务器成功')
                self.isOnline = True
                threading.Thread(target=self._recv).start()
                threading.Thread(target=self._heatBeat).start()
                break

    def _heatBeat(self):
        try:
            while self.isOnline:
                socket_client2.send("beat".encode())
                time.sleep(1)
        except Exception as message:
            print('连接服务器报错%s' % message)
            self.isOnline = False
            self.connect()

    """ socket发送数据 """

    def _send(self, msg):
        try:
            socket_client2.send(msg.encode())
            print('发送给服务器的消息：%s' % msg)
        except Exception as message:
            print('连接服务器报错%s' % message)
            self.isOnline = False
            self.connect()

    """ socket接收数据 """

    def _recv(self):
        try:
            while self.isOnline:
                res = socket_client2.recv(1024)
                if not res:
                    break
                print(datetime.datetime.now().strftime('%Y-%m-%d_%H_%M_%S') + ' 收到服务器的消息：%s' % res)

                strRes = res.decode()
                if strRes == 'start':
                    if not self.cvRtmp.isRunning:
                        print("开始运行ffmpeg")
                        threading.Thread(target=self.cvRtmp.start).start()
                    else:
                        print("已经运行ffmpeg")
                elif strRes == 'stop':
                    print("关闭FFMPEG")
                    self.cvRtmp.isRunning = False
            self.isOnline = False
        except Exception as message:
            print('收到服务器的消息报错%s' % message)
            self.isOnline = False
        self.connect()


if __name__ == '__main__':
    client = SocketClient("101.132.46.141", 9411)
    client.connect()

